package net.jsoft.pms.web.mysql.grouprelationship;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONObject;

import net.jsoft.platform.core.util.file.FileBase64Utils;
import net.jsoft.platform.core.util.platform.PlatformUtils;
import net.jsoft.platform.core.web.BaseController;
import net.jsoft.platform.security.entity.user.SysUser;
import net.jsoft.platform.security.repository.UserRepository;
import net.jsoft.pms.entity.grouprelationship.GroupRelationship;
import net.jsoft.pms.repository.grouprelationship.GroupRelationshipRepository;

@Controller
@RequestMapping("/groupRelationship")
public class GroupRelationshipController extends BaseController
{
    private String PREFIX = "/pms/mysql/groupRelationship/";

    @Autowired
    private GroupRelationshipRepository repository;
    @Autowired
    private UserRepository userRepository;

    /**
     * 跳转到计划管理首页
     */
    @RequestMapping("/list")
    public String list()
    {
        return PREFIX + "list";
    }

    @RequestMapping("/listData")
    @ResponseBody
    public JSONObject list(int pageSize, int pageNumber, final String sszb, final String beginDate, final String endDate, final String optUser, final String zt, final String edit)
            throws ParseException
    {
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        PageRequest request = new PageRequest(pageNumber - 1, pageSize, sort);

        Page<GroupRelationship> list = repository.findAll(new Specification<GroupRelationship>()
        {

            @Override
            public Predicate toPredicate(Root<GroupRelationship> root, CriteriaQuery<?> query, CriteriaBuilder cb)
            {
                Predicate p = null;
                Predicate p1 = null;
                Predicate p2 = null;
                Predicate p3 = null;
                //                Predicate p4 = null;
                try
                {
                    if (StringUtils.isNotEmpty(optUser))
                    {
                        SysUser user = userRepository.findOne(Long.parseLong(optUser));
                        //                        p4 = ;
                        p = cb.and(cb.equal(root.<SysUser> get("confirmedUser"), user));
                    }
                    if (StringUtils.isNotEmpty(zt))
                    {
                        if ("1".endsWith(zt))
                        {
                            p2 = cb.isNull(root.<Date> get("dealDate"));

                        }
                        else
                        {
                            p2 = cb.isNotNull(root.<Date> get("dealDate"));
                        }
                        p = p == null ? cb.and(p2) : cb.and(p, p2);

                    }
                    if (StringUtils.isNotEmpty(edit))
                    {
                        if ("2".endsWith(edit))
                        {
                            p3 = cb.equal(root.<Boolean> get("edit"), true);

                        }
                        else
                        {
                            p3 = cb.equal(root.<Boolean> get("edit"), false);
                        }
                        p = p == null ? cb.and(p3) : cb.and(p, p3);
                    }

                    if (StringUtils.isNotEmpty(beginDate) && StringUtils.isNotEmpty(endDate))
                    {
                        p1 = cb.between(root.get("confirmedDate").as(Date.class), PlatformUtils.getdate(beginDate), PlatformUtils.getdate(endDate));
                        //                        p = cb.or(p1);
                        p = p == null ? cb.and(p1) : cb.and(p, p1);

                    }

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
                return p;
            }
        }, request);

        JSONObject json = new JSONObject();
        json.put("rows", list.getContent()); //这里的 rows 和total 的key 是固定的 
        json.put("total", list.getTotalElements());
        return json;
    }

    @RequestMapping("/add")
    public String add(Model model)
    {
        return PREFIX + "add";
    }

    @RequestMapping("/addSave")
    @ResponseBody
    public String addSave(GroupRelationship groupRelationship, long userId) throws IOException, Exception
    {
        SysUser user = userRepository.findOne(userId);
        groupRelationship.setConfirmedUser(user);
        repository.save(groupRelationship);
        return "ok";
    }

    @RequestMapping("/uploadFile")
    @ResponseBody
    private Map<String, String> uploadFile(@RequestParam(value = "file") MultipartFile file) throws IOException, Exception
    {
        String fileStr = FileBase64Utils.encodeBase64File(file.getInputStream());
        Map<String, String> map = new HashMap<String, String>();
        map.put("fileStr", fileStr);
        map.put("fileName", file.getOriginalFilename());
        return map;
    }

    @RequestMapping("/edit")
    public String edit(long id, Model model)
    {
        GroupRelationship groupRelationship = repository.findOne(id);
        model.addAttribute("groupRelationship", groupRelationship);
        return PREFIX + "edit";
    }

    @RequestMapping("/editSave")
    @ResponseBody
    public String editSave(GroupRelationship groupRelationship, long userId) throws ParseException
    {
        SysUser user = userRepository.findOne(userId);
        groupRelationship.setConfirmedUser(user);
        repository.save(groupRelationship);
        return "ok";
    }

    @RequestMapping("/view")
    public String view(long id, Model model)
    {
        GroupRelationship groupRelationship = repository.findOne(id);
        model.addAttribute("groupRelationship", groupRelationship);
        return PREFIX + "view";
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(long id) throws ParseException
    {
        repository.delete(id);
        return "ok";
    }

    @RequestMapping("/download")
    @ResponseBody
    public void download(HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        String fileName = request.getParameter("fileName");
        String file = request.getParameter("file");
        InputStream is = FileBase64Utils.decoderBase64File(file);
        response.setContentType("application/force-download");// 设置强制下载不打开

        String rqHd = request.getHeader("Content-Disposition");
        if (rqHd != null)
        {
            String rqHeader = URLEncoder.encode(rqHd, "attachment;fileName=" + fileName);
            response.addHeader("Content-Disposition", rqHeader);
        }

        //        String rqHeader = URLEncoder.encode(rqHd,StandardCharsets.UTF_8.displayName());  
        //        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        try
        {
            bis = new BufferedInputStream(is);
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1)
            {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bis != null)
            {
                try
                {
                    bis.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (is != null)
            {
                try
                {
                    is.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("/deal")
    public String deal(long id, Model model)
    {
        GroupRelationship groupRelationship = repository.findOne(id);
        model.addAttribute("groupRelationship", groupRelationship);
        return PREFIX + "deal";
    }

    @RequestMapping("/dealSave")
    @ResponseBody
    public String dealSave(GroupRelationship groupRelationship) throws ParseException
    {
        GroupRelationship temp = repository.findOne(groupRelationship.getId());
        temp.setDealDate(new Date());
        temp.setEdit(groupRelationship.isEdit());
        repository.save(temp);
        return "ok";
    }
}
